package com.atguigu.lease.sustom.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.uilt.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 验证token拦截器
 * @ClassName AuthenticationInterceptor
 * @Author admin
 * @Date 2024/6/4
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    /**
     * 在控制器方法执行前,解析校验token是否合法
     * @param request token通常被放在请求头中
     * @param response
     * @param handler 控制器方法
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("access_token");

        if (token == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }else {
//            JwtUtil.parseToken(token); // 解析token
            Claims claims = JwtUtil.parseToken(token);
            Long userId = claims.get("userId", Long.class);
            String username = claims.get("username", String.class);
            // 从token的负载中取出登录对象信息,并存入ThreadLocal
            LoginUserContext.setLoginUser(new LoginUser(userId,username));
        }
        return true;
    }


    /**
     * 在控制器方法执行结束后,做一些收尾工作(任何情况都能执行的方法)
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除ThreadLocal中的数据
        LoginUserContext.clear();
    }
























}
